<template>
  <view class="payment-container">
    <view class="payment-header">
      <view class="payment-title">支付收银台</view>
      <view class="store-name">{{ orderData.shopName }}</view>
      <view class="total-amount">¥{{ orderData.totalPrice.toFixed(2) }}</view>
      <view class="countdown">剩余支付时间：{{ formatTime(countdown) }}</view>
    </view>

    <view class="payment-methods">
      <view class="payment-method" @click="selectPayment('wechat')" :class="{selected: selectedMethod === 'wechat'}">
        <image src="/static/wechat-pay.png" class="method-icon"></image>
        <text>微信支付</text>
        <view class="check-icon" v-if="selectedMethod === 'wechat'">✓</view>
      </view>
      
      <view class="payment-method" @click="selectPayment('unionpay')" :class="{selected: selectedMethod === 'unionpay'}">
        <image src="/static/unionpay.png" class="method-icon"></image>
        <text>银联支付</text>
        <view class="check-icon" v-if="selectedMethod === 'unionpay'">✓</view>
      </view>
    </view>

    <button class="confirm-payment" @click="confirmPayment">
      立即支付 {{ orderData.totalPrice.toFixed(2) }}元
    </button>
  </view>
</template>

<script>
	import Config from '@/Config.js'
export default {
  data() {
    return {
      orderData: {},
      countdown: 1800, // 30分钟 = 1800秒
      selectedMethod: 'wechat',
      timer: null
    };
  },
  onLoad(options) {
    if (options.data) {
      this.orderData = JSON.parse(decodeURIComponent(options.data));
    }
    this.startCountdown();
  },
  onUnload() {
    clearInterval(this.timer);
  },
  methods: {
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          clearInterval(this.timer);
          uni.showToast({
            title: '支付超时',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      }, 1000);
    },
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    selectPayment(method) {
      this.selectedMethod = method;
    },
    confirmPayment() {
      uni.showLoading({
        title: '支付中...'
      });
      
      // 模拟支付过程
      setTimeout(() => {
        uni.hideLoading();
        
        // 创建订单
        this.createOrder();
        // 等待3秒后跳转到订单页面
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/orders/index' // 替换为你的订单页面路径
          });
        }, 3000);
      }, 2000);
    },
    // 修改后的创建订单方法
    createOrder() {
      const userId = uni.getStorageSync('userId');
      const order = {
        id: Date.now().toString(),
        items: this.orderData.items,
        totalPrice: this.orderData.totalPrice,
        status: "进行中",
        shopName: this.orderData.shopName,
        createTime: new Date().toLocaleString()
      };

      // 获取用户当前数据
      uni.request({
        url: Config.api_host+`/users/${userId}`,
        success: (res) => {
          const user = res.data;
          user.order = user.order || [];
          user.order.push(order);

          // 更新用户订单数据
          uni.request({
            url: Config.api_host+`/users/${userId}`,
            method: 'PUT',
            data: user,
            success: () => {
              // 清空当前超市购物车
              this.clearCheckedItems();
              uni.showToast({ title: '支付成功' });
            }
          });
        }
      });
    },
    addOrderToUser(order) {
      uni.request({
        url: Config.api_host+`/users`,
        method: "GET",
        success: (res) => {
          const user = res.data;
          user.order = user.order || [];
          user.order.push(order);
          uni.request({
            url: Config.api_host+`/users`,
            method: "PUT",
            data: user,
            success: () => {
              console.log('订单已添加到用户订单数组中');
            },
            fail: (err) => {
              console.error('添加订单到用户订单数组失败', err);
            }
          });
        },
        fail: (err) => {
          console.error('获取用户信息失败', err);
        }
      });
    },
    // 修改后的清空购物车方法
    clearCheckedItems() {
      const userId = uni.getStorageSync('userId');
      const shopId = this.orderData.items[0]?.shopId;
      
      uni.request({
        url: Config.api_host+`/users/${userId}`,
        success: (res) => {
          const user = res.data;
          // 过滤掉当前超市已选商品
          user.cart = user.cart.filter(item => 
            item.shopId !== shopId || !item.selected
          );
          
          // 更新用户数据
          uni.request({
            url:Config.api_host+ `/users/${userId}`,
            method: 'PUT',
            data: user,
            success: () => {
              console.log('购物车清理成功');
            }
          });
        }
      });
    }
  }
};
</script>

<style>
/* 优化后的样式 */
.payment-container {
  background-color: #f4f4f4;
  padding: 20px;
}

.payment-header {
  background: #0091ff;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.payment-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: white;
 
}

.store-name {
  font-size: 16px;
  color:beige;
  margin-bottom: 5px;
}

.total-amount {
  font-size: 30px;
  font-weight: bold;
  color:whitesmoke;
  margin-bottom: 5px;
}

.countdown {
  font-size: 14px;
  color:whitesmoke;
}

.payment-methods {
  background-color: white;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f4f4f4;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.payment-method:last-child {
  border-bottom: none;
}

.payment-method.selected {
  background-color: #f4f4f4;
}

.method-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.check-icon {
  margin-left: auto;
  font-size: 20px;
  color: #00a65a;
}

.confirm-payment {
  background-color: #00a65a;
  color: white;
  padding: 12px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  width: 100%;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.confirm-payment:hover {
  background-color: #008d4c;
}
</style>    